﻿//-----------------------------------------------------------------------
// <copyright file="GuildRankRepository.cs" company="FastNET Services">
//     Copyright (c) 2008-2009. All Rights Reserved.
// </copyright>
// <license>
//     GPLv2
// </license>
// <warranty>
//     THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
//     BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
//     NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
//     DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//     OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </warranty>
//-----------------------------------------------------------------------
#region Usings

using System;
using System.Collections.Generic;
using System.Data.EntityClient;
using System.Linq;
using GateShift.Common.Repository;
using GateShift.Common.Repository.Interfaces.DataInterfaces;
using GateShift.Common.Repository.Interfaces.Repositories;
using GateShift.Services.GameData.Entities;

#endregion

namespace GateShift.Services.GameData.Repositories
{
    /// <summary>
    /// General repository for managing Guild Ranks
    /// </summary>
    internal class GuildRankRepository : IGuildRankRepository
    {
        #region CTor/DTor

        /// <summary>
        /// Initializes a new instance of the GuildRankRepository class
        /// </summary>
        /// <param name="connection">Reference to the common EntityConnection for the repository</param>
        internal GuildRankRepository(EntityConnection connection)
        {
            Connection = connection;
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets a reference to the common EntityConnection for the repository
        /// </summary>
        protected EntityConnection Connection { get; private set; }

        #endregion

        #region IGuildRankRepository Members

        /// <summary>
        /// Retrieves all the ranks for a specific guild
        /// </summary>
        /// <param name="GuildID">Identity of the guild to retrieve by</param>
        /// <returns>List of IGuildRankData with all matching results</returns>
        /// <exception cref="ArgumentNullException">Thrown if GuildID is null</exception>
        /// <exception cref="InvalidCastException">Thrown if GuildID is of the wrong type for this repository</exception>
        public IList<IGuildRankData> RetrieveByGuildID(Identity GuildID)
        {
            if (!GuildID.CanFitInInt64())
            {
                throw new InvalidCastException(string.Format("Identity for this type of repository requires it to be of Int64/int/Int16 Type. Currently is {0}.", GuildID.UnderlyingType()));
            }

            List<IGuildRankData> returnValues = new List<IGuildRankData>();

            // This has to be done here because LINQ does not support the inline case
            long searchID = GuildID;

            using (EntityDataAdapter dataSource = new EntityDataAdapter(Connection))
            {
                IEnumerable<GuildRank> query = from
                                                       guildRank
                                                       in
                                                   dataSource.GuildRanks
                                               where
                                                   guildRank.Guild.GuildID == searchID
                                               select
                                                   guildRank;

                foreach (GuildRank rank in query)
                {
                    returnValues.Add(rank);
                    dataSource.Detach(rank);
                }
            }

            return returnValues;
        }

        #endregion

        #region IRepository<IGuildRankData> Members

        /// <summary>
        /// Retrieves all instances of IGuildRankData from the repository
        /// </summary>
        /// <returns>List of the requested IGuildRankData</returns>
        public IList<IGuildRankData> Retrieve()
        {
            List<IGuildRankData> returnValues = new List<IGuildRankData>();

            using (EntityDataAdapter dataSource = new EntityDataAdapter(Connection))
            {
                foreach (GuildRank rank in from guildRank in dataSource.GuildRanks select guildRank)
                {
                    returnValues.Add(rank);
                    dataSource.Detach(rank);
                }
            }

            return returnValues;
        }

        /// <summary>
        /// Retrieves the requested IGuildRankData by an Identity
        /// </summary>
        /// <param name="ID">Identity to retrieve the data by</param>
        /// <returns>IGuildRankData instance or null if one was not found</returns>
        /// <exception cref="InvalidCastException">Thrown if the identity is of the wrong type for this datasource</exception>
        public IGuildRankData Retrieve(Identity ID)
        {
            if (!ID.CanFitInInt64())
            {
                throw new InvalidCastException(string.Format("Identity for this type of repository requires it to be of Int64/int/Int16 Type. Currently is {0}.", ID.UnderlyingType()));
            }

            // This has to be done here because LINQ does not support the inline case
            long searchID = ID;

            using (EntityDataAdapter dataSource = new EntityDataAdapter(Connection))
            {
                GuildRank foundRank = (from
                                              guildRank
                                              in
                                           dataSource.GuildRanks
                                       where
                                           guildRank.RankID == searchID
                                       select
                                           guildRank).FirstOrDefault();

                if (foundRank != null)
                {
                    dataSource.Detach(foundRank);
                }

                return foundRank;
            }
        }

        /// <summary>
        /// Deletes the requested IGuildRankData
        /// </summary>
        /// <param name="Data">IGuildRankData to delete from the repository</param>
        /// <exception cref="ArgumentNullException">Thrown if data is null</exception>
        /// <exception cref="InvalidCastException">Thrown if the data is of the wrong type for this datasource</exception>
        /// <exception cref="InvalidOperationException">Thrown if the IGuildRankData is new or already deleted</exception>
        public void Delete(IGuildRankData Data)
        {
            if (Data == null)
            {
                throw new ArgumentNullException("Data", "Must have a valid Data to delete");
            }

            if (!(Data is GuildRank))
            {
                throw new InvalidCastException("Data is not of type GuildRank. Cannot delete this object through this repository");
            }

            if (Data.IsNew)
            {
                throw new InvalidOperationException("Data cannot be new before deleting. There is nothing to delete.");
            }

            if (Data.IsDeleted)
            {
                throw new InvalidOperationException("Data already deleted.");
            }

            using (EntityDataAdapter dataSource = new EntityDataAdapter(Connection))
            {
                dataSource.Attach((GuildRank)Data);
                dataSource.DeleteObject(Data);
                dataSource.SaveChanges();
            }
        }

        /// <summary>
        /// Saves the requested IGuildRankData
        /// </summary>
        /// <param name="Data">IGuildRankData to save to the repository</param>
        /// <exception cref="ArgumentNullException">Thrown if data is null</exception>
        /// <exception cref="InvalidCastException">Thrown if the data is of the wrong type for this datasource</exception>
        public void Save(IGuildRankData Data)
        {
            if (Data == null)
            {
                throw new ArgumentNullException("Data", "Must have a valid Data to delete");
            }

            if (!(Data is GuildRank))
            {
                throw new InvalidCastException("Data is not of type GuildRank. Cannot save this object through this repository");
            }

            if (!Data.IsDirty)
            {
                return;
            }

            using (EntityDataAdapter dataSource = new EntityDataAdapter(Connection))
            {
                if (Data.IsNew)
                {
                    dataSource.AddToGuildRanks((GuildRank)Data);
                    dataSource.SaveChanges();
                    dataSource.Detach(Data);
                }
                else
                {
                    dataSource.ApplyPropertyChanges("GuildRanks", Data);
                    dataSource.SaveChanges();
                }
            }
        }

        /// <summary>
        /// Creates a new instance of IGuildRankData
        /// </summary>
        /// <returns>New Instance of IGuildRankData</returns>
        public IGuildRankData Create()
        {
            return new GuildRank();
        }

        #endregion
    }
}